<?php

class CompaniesController extends AppController {

    var $name = "Companies";
    public $helpers = array('Html', 'Form');

    public function index($company_id = null) {

        $this->paginate = array('Company' => array(
                'maxLimit' => 500,
                'limit' => 100,
                'recursive' => -1,
                'order' => array('Company.id'=>'DESC'),
                'joins' => array(
                    array('table' => 'cities', 'alias' => 'City', 'type' => 'left', 'conditions' => "Company.city_id=City.id"),
                    array('table' => 'departaments', 'alias' => 'Departament', 'type' => 'left', 'conditions' => "City.departament_id=Departament.id"),
                    array('table' => 'branches', 'alias' => 'Branch', 'type' => 'left', 'conditions' => "City.departament_id=Branch.departament_id"),
                ),
                'fields' => array('Company.id', 'Company.razon_social', 'Company.representante_legal', 'Company.nit', 'Departament.nombre', 'City.nombre'),
        ));

        if (is_null($company_id)) {
            if (empty($this->data)) {

                if ($this->Auth->user('group_id') == 5 or $this->Auth->user('group_id') == 8) {

                    $this->set('companies', $this->paginate());
                } else {

                    $this->set('companies', $this->paginate(array('Branch.id' => $this->Auth->user('branch_id'))));
                }
            } else {
                if ($this->Auth->user('group_id') == 5 or $this->Auth->user('group_id') == 8) {

                    $this->set('companies', $this->paginate(array('or' => array('Company.razon_social like' => '%' . $this->data['Company']['busqueda'] . '%', 'Company.representante_legal like' => '%' . $this->data['Company']['busqueda'] . '%', 'Company.nit like' => '%' . $this->data['Company']['busqueda'] . '%', 'Departament.nombre like' => '%' . $this->data['Company']['busqueda'] . '%', 'City.nombre like' => '%' . $this->data['Company']['busqueda'] . '%'))));
                } else {


                    $this->set('companies', $this->paginate(array('Branch.id' => $this->Auth->user('branch_id'), 'or' => array('Company.razon_social like' => '%' . $this->data['Company']['busqueda'] . '%', 'Company.representante_legal like' => '%' . $this->data['Company']['busqueda'] . '%', 'Company.nit like' => '%' . $this->data['Company']['busqueda'] . '%', 'Departament.nombre like' => '%' . $this->data['Company']['busqueda'] . '%', 'City.nombre like' => '%' . $this->data['Company']['busqueda'] . '%'))));
                }
            }
        } else {
            $this->set('companies', $this->paginate(array('Company.id' => $company_id)));
        }
    }

    public function add() {

        if (!empty($this->request->data)) {

            if ($this->Company->saveAll($this->request->data)) {
                $this->Session->setFlash('el registro se ha agregado correctamente.', 'flash_custom');
                $this->redirect(array('action' => 'index'));
            } else {

                $this->Session->setFlash('el registro se no se  ha agregado.', 'flash_custom');
                $this->redirect(array('action' => 'index'));
            }
        } else {
            
            $this->loadModel('Branch');
            $dep_id=$this->Branch->field('departament_id',array('Branch.id'=>$this->Auth->user('branch_id')));
            $this->set('departaments', $this->Company->City->Departament->find('list', array('conditions'=>array('Departament.id'=>$dep_id), 'fields' => array('Departament.id', 'Departament.nombre'))));
        }
    }

    public function view($id) {

        $this->set('company', $this->Company->find('first', array('fields' => array('Company.*', 'Departament.id'), 'recursive' => -1, 'conditions' => array('Company.id' => $id), 'joins' => array(array('table' => 'cities', 'alias' => 'City', 'type' => 'left', 'conditions' => "Company.city_id=City.id"), array('table' => 'departaments', 'alias' => 'Departament', 'type' => 'left', 'conditions' => "City.departament_id=Departament.id")))));
    }

    function delete($id) {
        if ($this->Company->delete($id)) {
            $this->Session->setFlash('La empresa con id: ' . $id . ' fue eliminada.');
            $this->redirect(array('action' => 'index'));
        }
    }

    public function edit($id) {
        $this->layout = "ajax";
        if (empty($this->data)) {
            $this->set('departaments', $this->Company->City->Departament->find('list', array('fields' => array('Departament.id', 'Departament.nombre'))));
            $this->set('cities', $this->Company->City->find('list', array('fields' => array('City.id', 'City.nombre'), 'conditions' => array())));

            $this->data = $this->Company->find('first', array('fields' => array('Company.*', 'Departament.id'), 'recursive' => -1, 'conditions' => array('Company.id' => $id), 'joins' => array(array('table' => 'cities', 'alias' => 'City', 'type' => 'left', 'conditions' => "Company.city_id=City.id"), array('table' => 'departaments', 'alias' => 'Departament', 'type' => 'left', 'conditions' => "City.departament_id=Departament.id"))));
        } else {

            if ($this->Company->save($this->data)) {
                $this->Session->setFlash('La empresa ha sido actualizada.', 'flash_custom');
                $this->redirect(array('controller' => 'companies', 'action' => 'edit_poll', $this->data['Company']['id']));
            }
        }
    }

    public function select() {
        $this->layout = "ajax";

        $this->set('cities', $this->Company->City->find('list', array('fields' => array('City.id', 'City.nombre'), 'conditions' => array('City.departament_id' => $this->data['Company']['departament_id']))));
    }

    function edit_poll($company_id) {
        $this->layout = "ajax";
        $this->set("company_id", $company_id);
        $this->set("company", $this->Company->find('first', array('fields' => array('Company.razon_social', 'Company.id'), 'recursive' => -1, 'conditions' => array('Company.id' => $company_id))));
    }

    public function financiera($id) {
        $this->layout = "ajax";
        $this->Company->recursive = -1;
        if (empty($this->data)) {

            $this->data = $this->Company->find('first', array('conditions' => array('Company.id' => $id), 'fields' => array('Company.fecha_ultima_asamblea', 'Company.estatutos_vigentes', 'Company.fecha_actualizacion', 'Company.gestion_contable', 'Company.libro_contable', 'Company.libro_cual', 'Company.dt_libros', 'Company.monto_patrimonio', 'Company.activos', 'Company.pasivos', 'Company.estados_finacieros', 'Company.presenta_estados', 'Company.gestion_administrativa', 'Company.empleados_activos', 'Company.adeuda_impuestos', 'Company.tiene_creditos', 'Company.credito_banco', 'Company.credito_particular', 'Company.adeuda_servicios', 'Company.tiene_gavamenes', 'Company.hipoteca', 'Company.embargo', 'Company.otras_deudas', 'Company.revision_fiscal', 'Company.Junta_vigilancia', 'Company.otro_autocontrol', 'Company.observacion_financieras', 'Company.id')));
        } else {

            if ($this->Company->save($this->data)) {
                $this->Session->setFlash('La empresa ha sido actualizada.', 'flash_custom');
                $this->redirect(array('controller' => 'companies', 'action' => 'edit_poll', $this->data['Company']['id']));
            } else {
                $this->Session->setFlash('Error editando datos');
            }
        }
    }

    public function desarrollo_comunitario($id) {
        $this->layout = "ajax";
        $this->Company->recursive = -1;
        if (empty($this->data)) {

            $this->data = $this->Company->find('first', array('conditions' => array('Company.id' => $id), 'fields' => array('Company.capacitacion', 'Company.cual_capacitacion', 'Company.recibo_apoyo', 'Company.id', 'Company.cual_apoyo', 'Company.observacion_desarrollo')));
        } else {

            if ($this->Company->save($this->data)) {
                $this->Session->setFlash('La empresa ha sido actualizada.', 'flash_custom');
                $this->redirect(array('controller' => 'companies', 'action' => 'edit_poll', $this->data['Company']['id']));
            } else {
                $this->Session->setFlash('Error editando datos');
            }
        }
    }

    function comunidad_excluida($id) {
        $this->layout = "ajax";
        $this->Company->recursive = -1;
        if (empty($this->data)) {

            $this->data = $this->Company->find('first', array('conditions' => array('Company.id' => $id), 'fields' => array('Company.asociados_inactivos', 'Company.asociados_fallecidos', 'Company.asociados_desplazados', 'Company.asociados_renunciaron', 'Company.asociados_desafiliados', 'Company.asociados_sancionados', 'Company.asociados_observacion', 'Company.id', 'Company.familias_desplazadas', 'Company.familias_afro', 'Company.familias_indigenas', 'Company.familias_campesinas', 'Company.familias_desmovilizadas')));
        } else {

            if ($this->Company->save($this->data)) {
                $this->Session->setFlash('Registro editado correctamente', 'flash_custom');
                $this->redirect(array('controller' => 'companies', 'action' => 'edit_poll', $this->data['Company']['id']));
            } else {
                $this->Session->setFlash('Error editando datos');
            }
        }
    }

    function principales_dificultades($company_id) {
        $this->layout = "ajax";
        $this->Company->recursive = -1;
        if (empty($this->data)) {

            $this->data = $this->Company->find('first', array('conditions' => array('Company.id' => $company_id), 'fields' => array('Company.orden_publico', 'Company.autodiagnostico_calificacion', 'Company.adjunto_aviso', 'Company.adjunto_encuesta', 'Company.inseguridad', 'Company.conflictos_internos', 'Company.agricolas', 'Company.serv_publicos', 'Company.organizacionales', 'Company.otras_dificultades', 'Company.observaciones_dificultades', 'Company.autodiagnostico', 'Company.nombre_encuestado', 'Company.id')));
        } else {

            $rutaArchivo = APP . "webroot" . DS . "files" . DS . "Empresa-" . $company_id;
            if (!is_dir($rutaArchivo)) {
                if (!mkdir($rutaArchivo)) {
                    echo "error creando archivo";
                    //redirect
                }
            }
            $nombrearchivo = "Encuesta_" . $company_id . ".pdf";
            $nombrearchivo1 = "Aviso_" . $company_id . ".pdf";
            if ($this->Company->save($this->data)) {

                $exito = 1;

                if (!empty($this->data['Company']['archivo_encuesta']['tmp_name'])) {

                    if (move_uploaded_file($this->data['Company']['archivo_encuesta']['tmp_name'], $rutaArchivo . DS . $nombrearchivo)) {
                        
                        $data=array('Company'=>array(
                            'id'=>$company_id,
                            'adjunto_encuesta'=>$nombrearchivo,
                        ));
                        $this->Company->save($data);
                        
                    } else {
                        $exito = 0;
                    }
                }
                if (!empty($this->data['Company']['archivo_aviso']['tmp_name'])) {

                    if (move_uploaded_file($this->data['Company']['archivo_aviso']['tmp_name'], $rutaArchivo . DS . $nombrearchivo1)) {
                       
                        $data=array('Company'=>array(
                            'id'=>$company_id,
                            'adjunto_aviso'=>$nombrearchivo1,
                        ));
                        $this->Company->save($data);
                    } else {
                        $exito = 0;
                    }
                }


                if ($exito) {
                    $this->Session->setFlash('Registro editado correctamente', 'flash_custom');
                    $this->redirect(array('controller' => 'companies', 'action' => 'edit_poll', $this->data['Company']['id']));
                } else {

                    $this->Session->setFlash('Eror adjuntando documento', 'flash_custom');
                    $this->redirect(array('controller' => 'companies', 'action' => 'edit_poll', $this->data['Company']['id']));
                }
            } else {
                $this->Session->setFlash('Error editando datos');
            }
        }
    }

    function edit_activity($company_id) {
        $this->layout = "ajax";

        if (empty($this->data)) {

            $this->data = $this->Company->find('first', array('conditions' => array('Company.id' => $company_id), 'fields' => array('Company.id', 'Company.produccion', 'Company.transformacion', 'Company.comercializacion', 'Company.servicios', 'Company.otra', 'Company.cual', 'Company.comunitaria', 'Company.individual', 'Company.porc_explotado', 'Company.arrendado', 'Company.sin_explotar', 'Company.recibio_capital', 'Company.desarrolla_proyecto', 'Company.cual_proyecto', 'Company.asistencia_tecnica', 'Company.entidad_presto', 'Company.genera_ingresos', 'Company.participado_ec_proyecto', 'Company.ayuda_gobierno', 'Company.ayuda_privada', 'Company.ayuda_otra', 'Company.observaciones_actividad', 'Company.cual_explotacion', 'Company.cual')));
        } else {

            if ($this->Company->save($this->data)) {
                $this->Session->setFlash('La actividad ha sido actualizada.', 'flash_custom');
                $this->redirect(array('controller' => 'companies', 'action' => 'edit_poll', $company_id));
            }
        }
    }

    function total_report() {
        $this->layout = "csv";
        ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
        //create a file
        $filename = "Reporte_empresas_" . date("Y.m.d") . ".csv";
        $csv_file = fopen('php://output', 'w');
        $this->response->type('application/csv');


        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $cabecera = array();
        $sql = "SELECT c.nombre as Departamento, b.nombre as Municipio, razon_social as Razón_social, nit As NIT, objeto_social AS Objeto, direccion AS Dirección,  representante_legal AS Representante, fecha_constitucion AS Fecha_constitución, telefonos AS Teléfonos , autodiagnostico_calificacion AS Autodiagnostico,autodiagnostico As Autodiagnóstico_Observacion FROM "
                . "companies a LEFT JOIN cities b on a.city_id=b.id  LEFT JOIN departaments c on c.id=b.departament_id   "
                . " WHERE 1=1 ORDER BY c.nombre ASC , b.id DESC";
        $flag = 0;
        $resultados = $this->Company->query($sql);
        foreach ($resultados as $key => $value) {
            $cabecera = array();
            $datos = array();
            foreach ($value as $key1 => $value1) {

                foreach ($value1 as $key2 => $value2) {
                    $cabecera[] = ($key2);
                    ;
                    $datos[] = utf8_decode($value2);
                }
            }

            if ($flag == 0) {
                fputcsv($csv_file, $cabecera, ';', '"');
                $flag = 1;
            }
            fputcsv($csv_file, $datos, ';', '"');
        }
        //var_dump($cabecera);

        fclose($csv_file);
        $this->autoRender = false;
    }

    function departament_report() {
        $this->layout = "ajax";
        ini_set('max_execution_time', 600); //increase max_execution_time to 10 min if data set is very large
        //create a file
        $filename = "Reporte_empresas_" . date("Y.m.d") . ".csv";
        $csv_file = fopen('php://output', 'w');
        $this->response->type('application/csv');


        header('Content-Disposition: attachment; filename="' . $filename . '"');

        $cabecera = array();
        $sql = "SELECT c.nombre AS Departamento, COUNT( * ) AS Número
        FROM  companies a
        LEFT JOIN cities b ON a.city_id = b.id
        LEFT JOIN departaments c ON c.id = b.departament_id
        WHERE 1=1 
        GROUP BY c.id,c.nombre
        ORDER BY c.id";
        $flag = 0;
        $resultados = $this->Company->query($sql);
        foreach ($resultados as $key => $value) {
            $cabecera = array();
            $datos = array();
            foreach ($value as $key1 => $value1) {

                foreach ($value1 as $key2 => $value2) {
                    $cabecera[] = ($key2);
                    ;
                    $datos[] = utf8_decode($value2);
                }
            }

            if ($flag == 0) {
                fputcsv($csv_file, $cabecera, ';', '"');
                $flag = 1;
            }
            fputcsv($csv_file, $datos, ';', '"');
        }
        //var_dump($cabecera);

        fclose($csv_file);
        $this->autoRender = false;
    }

    function report_index() {
        $this->layout = "ajax";
        $sql = "SELECT c.nombre AS Departamento, COUNT( * ) AS Num
        FROM  companies a
        LEFT JOIN cities b ON a.city_id = b.id
        LEFT JOIN departaments c ON c.id = b.departament_id
        WHERE 1=1 
        GROUP BY c.id,c.nombre
        ORDER BY c.id";
        $flag = 0;

        $resultados = $this->Company->query($sql);
        $str = "";
        foreach ($resultados as $res) {

            $str.="['" . $res[0]['Departamento'] . "'," . $res[0]['Num'] . "],";
        }

        $this->set('datos', $str);
    }

}

?>